import axios from 'axios'
import qs from 'qs'
// import router from '@/router/index'
// import store from '@/store/index'
import { Message } from 'element-ui'

function showTip(message) {
  if (!message) {
    return
  }
  Message({
    message,
    type: 'error',
    duration: 3 * 1000
  })
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data || {}
    if (res.code !== 200) {
      showTip(res.message)
      return Promise.reject(res)
    }
    res.responseHeaders = response.headers
    return res
  },
  (error) => {
    console.log(message, error)
    let message = error.message
    message && showTip(message)
    return Promise.reject(error)
  }
)

export const httpPost = (url, data, options = {}, header = {}) => {
  const { contentType = 'application/x-www-form-urlencoded', responseType = 'json' } = options
  return service({
    url,
    data,
    method: 'post',
    responseType,
    transformRequest: [
      (data) => {
        if (contentType === 'application/x-www-form-urlencoded') {
          return qs.stringify(data)
        }
        return JSON.stringify(data)
      }
    ],
    headers: {
      'Content-Type': contentType,
      ...header
    }
  })
}

export const httpGet = (url, params, options = {}, header = {}) => {
  const { contentType = 'application/json', responseType = 'json' } = options
  return service({
    url,
    params,
    method: 'get',
    responseType,
    headers: {
      'Content-Type': contentType,
      ...header
    }
  })
}

export default service
